package com.yxjx.duoxue.my;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.Executors;

import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;
import com.tencent.stat.StatAccount;
import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.Yx;
import com.yxjx.duoxue.course.CourseIntroductionActivity;
import com.yxjx.duoxue.course.CourseListActivity;
import com.yxjx.duoxue.customview.autolist.AutoListView;
import com.yxjx.duoxue.customview.autolist.AutoListView.OnLoadListener;
import com.yxjx.duoxue.customview.autolist.AutoListView.OnRefreshListener;
import com.yxjx.duoxue.datamodel.DMBaiduLocation;
import com.yxjx.duoxue.datamodel.course.DMCourse;
import com.yxjx.duoxue.my.FavouriteCoursesActivity.FavouriteListAsyncTask;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.network.URMobileCheckResponse;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.network.UserReg;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;

public class AppointedCourses extends BaseActionBarActivity implements
		OnRefreshListener, OnLoadListener {
	
	public static final int PAGE_ACTIVITY_NUM = 20;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_appoint_courses);
		
		mList = (AutoListView) findViewById(R.id.list);
		mAdapter = new AppointCoursesAdapter();
		mList.setAdapter(mAdapter);
		mList.setOnRefreshListener(this);
		mList.setOnLoadListener(this);
		mList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				
				if (arg2 >= mAdapter.getCount() + 1 || arg2 == 0) {
					return;
				}
				
				DMCourse course = mAdapter.getData().get(arg2 - 1);
				Intent intent = new Intent(getApplicationContext(), CourseIntroductionActivity.class);
				intent.putExtra(NwUtils.KEY_ID, "" + course.getCourseId());
				startActivity(intent);
				
			}
		});

		mULrsp = UserLoginResponse.getInstance(getApplicationContext());
		JSONObject params = new JSONObject();
		try {
			params.put("startIndex", "1");
			params.put("count", "10");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		customizeActionBarTitle("免费预约试听");
		requestAllCourses();
		
		Utils.registerPreferenceChangeListener(getApplicationContext(), mLocationChangeListener);
	}
	
	class AppointCoursesAdapter extends BaseAdapter {
		
		ArrayList<DMCourse> mCourses = new ArrayList<DMCourse>();
		
		public ArrayList<DMCourse> getData() {
			return mCourses;
		}
		
		public void setData(ArrayList<DMCourse> courses) {
			mCourses = courses;
			notifyDataSetChanged();
		}
		
		public void addData(ArrayList<DMCourse> courses) {
			mCourses.addAll(courses);
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			return mCourses == null ? 0: mCourses.size();
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret;
			if (arg1 == null) {
//				ret = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_appoint_audition, null);
				ret = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_course_list_1, null);
			} else {
				ret = arg1;
			}
			
		
			DMCourse course = mCourses.get(arg0);
			UIHelper.setText(ret, R.id.course_name, course.getCourseName());
			((TextView) ret.findViewById(R.id.category)).setText(Utils.getCategoryText(course));
			UIHelper.setText(ret, R.id.school_name, course.getSchoolFullName());
			UIHelper.asyncLoadImage((ImageView) ret.findViewById(R.id.icon), course.getHeadImageUrl(), R.drawable.default_icon);
			((TextView) ret.findViewById(R.id.location_info)).setText(Utils.getDistanceDesc(getApplicationContext(), course.getSchoolGps()));
			return ret;
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

	}
	
	private void requestAllCourses() {
		JSONObject param = new JSONObject();
		try {
			param.put("startIndex", "1");
			param.put("count","20");
			param.put("time", "" + System.currentTimeMillis());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		requestCoursesByParams(param, AutoListView.REFRESH);
	}
	
	private void requestsMoreCourses() {
		JSONObject param = new JSONObject();
		int startIndex = mAdapter.getCount() + 1;
		try {
			param.put("startIndex", "" + startIndex);
			param.put("count","20");
			param.put("time", "" + System.currentTimeMillis());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		requestCoursesByParams(param, AutoListView.LOAD);
	}
	
	private void requestCoursesByParams(JSONObject params, int callbackId) {
		BookItemsAsyncTask<DMCourse> task = new BookItemsAsyncTask<DMCourse>();
		task.execute(params.toString(), "" + callbackId);
	}
	
	private Handler mHandler = new Handler() {
    	@Override
    	public void handleMessage(android.os.Message msg) {
    		ArrayList<DMCourse> result = (ArrayList<DMCourse>) msg.obj;
    		switch (msg.what) {
			case AutoListView.REFRESH:
				removeMessages(AutoListView.REFRESH);
				mAdapter.setData(result);
				mList.onRefreshComplete();
				// try to progress dialog
				dismissDialog(result);
				resetScroll();
				break;
			case AutoListView.LOAD:
				removeMessages(AutoListView.LOAD);
				mAdapter.addData(result);
				mList.onLoadComplete();
				dismissDialog(result);
				break;
			default:
				break;
			}
    		if (result == null) {
    			mList.setResultSize(0);
    		} else {
    			mList.setResultSize(result.size());
    		}
    	}
    };
	
	class BookItemsAsyncTask<E> extends AsyncTask<String, Integer, ArrayList<E>> {
		
		private int mCallbackId;

		@Override
		protected ArrayList<E> doInBackground(String... arg0) {
			
			String jsonString = arg0[0];
			mCallbackId = Integer.valueOf(arg0[1]);
			JSONObject params;
			// 封装参数
			try {
				params = new JSONObject(jsonString);
			} catch (JSONException e) {
				// 参数错误
				return null;
			}
			
			// book info list. 
			ArrayList<DMCourse> courses = new ArrayList<DMCourse>();
			try {
				courses = UserReg.requestBookedInfos(mULrsp, null, Yx.TYPE_ITEM_COURSE, params, AppointedCourses.this);
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return (ArrayList<E>) courses;
		}
		
		@Override
		protected void onPostExecute(ArrayList<E> result) {
			super.onPostExecute(result);
			mHandler.sendMessage(mHandler.obtainMessage(mCallbackId, result));
		}
		
	}
	
	private void dismissDialog(ArrayList<DMCourse> data) {
		findViewById(R.id.loading).setVisibility(View.INVISIBLE);
		if (data == null || data.size() == 0) {
			findViewById(R.id.empty).setVisibility(View.VISIBLE);
			findViewById(R.id.list).setVisibility(View.INVISIBLE);
		} else {
			findViewById(R.id.list).setVisibility(View.VISIBLE);
			findViewById(R.id.empty).setVisibility(View.INVISIBLE);
		}
	}
	
	private UserLoginResponse mULrsp;
	private AppointCoursesAdapter mAdapter;

	private View.OnClickListener mClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			switch(arg0.getId()) {
			default:
				mBaseClickListener.onClick(arg0);
				break;
			}
		}
	};
	
	public void toFind(View view) {
		UIHelper.LoadingActivity(AppointedCourses.this, new Intent(
				getApplicationContext(), CourseListActivity.class));
		finish();
	}
	
	private AutoListView mList;

	@Override
	public void onLoad() {
		requestsMoreCourses();
	}

	@Override
	public void onRefresh() {
		requestAllCourses();

	}
	
	private void resetScroll() {
		mList.post(new Runnable() {
			
			@Override
			public void run() {
				mList.setSelection(0);
			}
		});
	}
	
	private SharedPreferences.OnSharedPreferenceChangeListener mLocationChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {

		@Override
		public void onSharedPreferenceChanged(
				SharedPreferences sharedPreference, String key) {
			DMBaiduLocation location = DMBaiduLocation.forceGetLocationFromSharedPreference(AppointedCourses.this);
			onRelocationDone(location);
		}
	};
	
	private void onRelocationDone(DMBaiduLocation location) {
		mAdapter.notifyDataSetInvalidated();
	}

}
